package com.bdqn.wr.security;

import com.alibaba.fastjson.JSON;
import com.bdqn.wr.Dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserService implements UserDetailsService { //自定义UserDetailsService 接口

    @Autowired
    UserDao userDao;
    @Autowired
    HttpServletRequest request;//可以调用session

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        com.bdqn.wr.entity.User user = userDao.findByUserName(username);
        System.out.println(JSON.toJSONString(user));
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        System.out.println(user.getRole().getName());
        //        原来他会把设置的角色名自动加上 ‘ ROLE_ ’ 前缀。
        //所以在数据库中将角色名设置为带 ‘ ROLE_ ’ 前缀的值便能成功访问限制的地址
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole().getName()));
        return new org.springframework.security.core.userdetails.User(user.getInfo().getUsername(),
                encoder.encode(user.getInfo().getPassword()), authorities);
    }
}

